<template>
  <div class="message-container">
    <div class="conversation-list">
      <el-input
        v-model="searchUser"
        placeholder="搜索用户名"
        clearable
        class="search-input"
      ></el-input>
      <el-menu
        class="convo-menu"
        :default-active="activeConvoId"
        @select="selectConvo"
      >
        <template v-if="filteredConvoUsers.length > 0">
          <el-menu-item
            v-for="user in filteredConvoUsers"
            :key="user"
            :index="String(user)"
          >
            <div class="convo-item">
              <span>{{ userNames[user] || `用户${user}` }}</span>
              <span class="unread-count" v-if="getUnreadCount(user) > 0">
                {{ getUnreadCount(user) }}
              </span>
            </div>
          </el-menu-item>
        </template>
        <div v-else class="no-contacts">
          无联系人
        </div>
      </el-menu>
    </div>
    <div class="chat-panel">
      <div class="chat-window">
        <div v-if="activeConvoId" class="messages">
          <div
            v-for="msg in conversations"
            :key="msg.message_id"
            :class="['message-item', msg.sender_id == currentUser ? 'outgoing' : 'incoming']"
          >
            <div class="message-content">
              <p class="content">{{ msg.content }}</p>
              <div class="message-info">
                <span class="time">{{ formatDate(msg.send_time) }}</span>
                <span v-if="msg.sender_id == currentUser" class="read-status">
                  {{ msg.is_read ? '已读' : '未读' }}
                </span>
              </div>
            </div>
          </div>
        </div>
        <div v-else class="no-convo">
          请选择左侧的用户查看会话
        </div>
      </div>
      <!-- 输入区 -->
      <div class="chat-input">
        <el-input
          type="textarea"
          rows="2"
          v-model="newMessage"
          placeholder="输入消息并回车发送"
          @keyup.enter.native="sendMessage"
          :disabled="!activeConvoId"
        ></el-input>
        <el-button 
          type="primary" 
          @click="sendMessage" 
          :disabled="!newMessage.trim() || !activeConvoId"
          class="send-button"
        >
          发送
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useAuthStore } from '../store/auth'
import { ElMessage } from 'element-plus'

const auth = useAuthStore()
const currentUser = auth.userId

const allMessages = ref([])
const convoUsers = ref([])
const searchUser = ref('')
const activeConvoId = ref(null)
const conversations = ref([])
const newMessage = ref('')
const loading = ref(false)
const unreadCounts = ref({})
const userNames = ref({})

// 获取用户信息
const fetchUserInfo = async (userId) => {
  try {
    const token = auth.token
    const res = await fetch(`http://127.0.0.1:8000/api/users/${userId}`, {
      headers: { 'Authorization': `Bearer ${encodeURIComponent(token)}` }
    })
    if (!res.ok) throw new Error(await res.text())
    const userData = await res.json()
    userNames.value[userId] = userData.username
  } catch (err) {
    console.error('获取用户信息失败:', err)
    userNames.value[userId] = `用户${userId}` // 如果获取失败，显示默认名称
  }
}

// 获取收到的消息，用于构建会话列表
const fetchMessages = async () => {
  try {
    const token = auth.token
    const res = await fetch(`http://127.0.0.1:8000/api/messages?user_id=${currentUser}`, {
      headers: { 'Authorization': `Bearer ${encodeURIComponent(token)}` }
    })
    if (!res.ok) throw new Error(await res.text())
    allMessages.value = await res.json()
    
    // 提取所有对话用户（包括发送和接收）
    const users = new Set()
    allMessages.value.forEach(msg => {
      if (msg.sender_id !== currentUser) users.add(msg.sender_id)
      if (msg.receiver_id !== currentUser) users.add(msg.receiver_id)
    })
    convoUsers.value = Array.from(users)
    
    // 获取所有用户的用户名
    for (const userId of convoUsers.value) {
      await fetchUserInfo(userId)
    }
    
    // 计算每个用户的未读消息数
    const counts = {}
    allMessages.value.forEach(msg => {
      if (msg.receiver_id === currentUser && !msg.is_read) {
        const otherUserId = msg.sender_id
        counts[otherUserId] = (counts[otherUserId] || 0) + 1
      }
    })
    unreadCounts.value = counts
  } catch (err) {
    ElMessage.error('获取消息列表失败: ' + err.message)
  }
}

// 筛选会话列表
const filteredConvoUsers = computed(() => {
  if (!searchUser.value) return convoUsers.value
  return convoUsers.value.filter(u => String(u).includes(searchUser.value))
})

// 获取未读消息数量
const getUnreadCount = (userId) => {
  return unreadCounts.value[userId] || 0
}

// 标记消息为已读
const markMessageAsRead = async (messageId) => {
  try {
    const token = auth.token
    const res = await fetch(
      `http://127.0.0.1:8000/api/messages/${messageId}/read`,
      {
        method: 'PUT',
        headers: { 'Authorization': `Bearer ${encodeURIComponent(token)}` }
      }
    )
    if (!res.ok) throw new Error(await res.text())
  } catch (err) {
    console.error('标记已读失败:', err)
  }
}

// 选择会话：获取两人所有消息
const selectConvo = async (userId) => {
  activeConvoId.value = parseInt(userId)
  try {
    loading.value = true
    const token = auth.token
    const res = await fetch(
      `http://127.0.0.1:8000/api/conversations?user1=${currentUser}&user2=${userId}`,
      { headers: { 'Authorization': `Bearer ${encodeURIComponent(token)}` } }
    )
    if (!res.ok) throw new Error(await res.text())
    conversations.value = await res.json()
    
    // 标记收到的消息为已读
    conversations.value.forEach(msg => {
      if (msg.receiver_id === currentUser && !msg.is_read) {
        markMessageAsRead(msg.message_id)
      }
    })
  } catch (err) {
    ElMessage.error('获取会话失败: ' + err.message)
  } finally {
    loading.value = false
  }
}

// 发送消息
const sendMessage = async () => {
  if (!newMessage.value.trim() || !activeConvoId.value) return
  
  try {
    loading.value = true
    const token = auth.token
    const res = await fetch(
      `http://127.0.0.1:8000/api/messages?sender_id=${currentUser}&receiver_id=${activeConvoId.value}`, {
        method: 'POST',
        headers: { 
          'Content-Type': 'application/json', 
          'Authorization': `Bearer ${encodeURIComponent(token)}` 
        },
        body: JSON.stringify({ 
          content: newMessage.value.trim(),
          related_job_id: null,
          receiver_id: activeConvoId.value
        })
      }
    )
    if (!res.ok) throw new Error(await res.text())
    const msg = await res.json()
    conversations.value.push(msg)
    newMessage.value = ''
    
    // 更新未读消息计数
    if (unreadCounts.value[activeConvoId.value]) {
      unreadCounts.value[activeConvoId.value] = 0
    }
  } catch (err) {
    ElMessage.error('发送失败: ' + err.message)
  } finally {
    loading.value = false
  }
}

onMounted(fetchMessages)

// 格式化日期
const formatDate = (dt) => dt ? new Date(dt).toLocaleString('zh-CN') : ''
</script>

<style scoped>
.message-container {
  display: flex;
  height: 80vh;
  max-width: 1200px;
  margin: 20px auto;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.conversation-list {
  width: 250px;
  border-right: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
  background-color: rgba(255, 255, 255, 0.6); /* 添加背景色并设置透明度 */
}

.search-input {
  margin: 10px;
  width: 200px; /* 设置搜索框宽度 */
  align-self: center; /* 居中显示 */
}

.convo-menu {
  flex: 1;
  overflow: auto;
  border-right: none;
  background-color: rgba(255, 255, 255, 0.6); /* 添加背景色并设置透明度 */
}

.no-contacts {
  padding: 20px;
  text-align: center;
  color: #909399;
}

.chat-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-window {
  flex: 1;
  padding: 20px;
  overflow: auto;
  display: flex;
  flex-direction: column;
  background-color: rgba(255, 255, 255, 0.5); /* 白色，50% 透明度 */
}

.messages {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  min-height: 100%;
}

.message-item {
  margin-bottom: 15px;
  max-width: 70%;
  align-self: flex-start;
}

.message-item.outgoing {
  align-self: flex-end;
}

.message-item.incoming .content {
  background: #f0f0f0;
  border-radius: 8px 8px 8px 0;
}

.message-item.outgoing .content {
  background: #409EFF;
  color: #fff;
  border-radius: 8px 8px 0 8px;
}

.content {
  display: inline-block;
  padding: 10px 15px;
  word-break: break-word;
}

.time {
  display: block;
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.no-convo {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 16px;
}

.chat-input {
  padding: 15px;
  border-top: 1px solid #ebeef5;
  background: #f5f7fa;
  display: flex;
  gap: 10px;
}

.read-status {
  font-size: 12px;
  color: #909399;
  margin-left: 8px;
}

.convo-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.unread-count {
  background-color: #f56c6c;
  color: white;
  border-radius: 10px;
  padding: 2px 6px;
  font-size: 12px;
  min-width: 18px;
  text-align: center;
}

.message-content {
  display: flex;
  flex-direction: column;
  max-width: 100%;
}

.message-info {
  display: flex;
  align-items: center;
  margin-top: 4px;
}

.send-button {
  align-self: flex-end;
}
</style>